import { useState, useEffect } from "react";
import { roleApi } from "@/api/role";
import type { Role } from "@/types/role";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { sessionApi } from "@/api/session";
import { useNavigate } from "react-router";
import { useConversationStore } from "@/store/useConversationStore";

export default function RoleScreen() {
  const navigate = useNavigate();
  const [roles, setRoles] = useState<Role[]>([]);
  const { setSelectedId, addConversation } = useConversationStore();

  useEffect(() => {
    roleApi.getRoleList().then((res) => {
      setRoles(res.data || []);
    });
  }, []);

  const handleCardClick = async (role: Role) => {
    if (role.id) {
      const { data } = await sessionApi.createChat(role.id);
      console.log(data, "role");
      const { SessionId, Role } = data;
      setSelectedId(SessionId);
      addConversation({
        id: SessionId,
        roleName: Role.name,
        roleAvatarUrl: Role.avatar_url,
        roleId: Role.id,
      });
      navigate(`/conversation/${SessionId}`);
    }
  };

  return (
    <div className="w-full h-screen bg-gray-50 flex flex-col overflow-x-hidden">
      {/* 顶部标题 */}
      <header className="p-6 border-b bg-white shadow-sm">
        <h1 className="text-2xl font-bold">🎤 在线角色列表</h1>
        <p className="text-gray-500 text-sm mt-1">请选择一个角色开始语音聊天</p>
      </header>

      {/* 角色网格 */}
      <main className="flex-1 overflow-y-auto p-6">
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
          {roles.map((role) => (
            <Card
              onClick={() => handleCardClick(role)}
              key={role.id}
              className="hover:shadow-lg transition-shadow cursor-pointer"
            >
              <CardHeader className="flex flex-row items-center gap-4">
                <Avatar className="h-12 w-12">
                  <AvatarImage src={role.avatar_url} alt={role.name} />
                  <AvatarFallback>{role.name?.charAt(0) || "?"}</AvatarFallback>
                </Avatar>
                <div>
                  <CardTitle className="text-lg">{role.name}</CardTitle>
                  <Badge variant="default" className="mt-1">
                    在线
                  </Badge>
                </div>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-gray-600 line-clamp-2">
                  {role.description || "这个角色没有简介"}
                </p>
              </CardContent>
            </Card>
          ))}
        </div>
      </main>
    </div>
  );
}
